﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace MSTR.IS.Util
{
    public static class Paging
    {
        /// <summary>
        /// Gets the query for a specified page of data.
        /// </summary>
        /// <typeparam name="T">The type of the data in the data source.</typeparam>
        /// <param name="source">The data source.</param>
        /// <param name="pageSize">Maximum records of single page, must be greater than zero.</param>
        /// <param name="pageIndex">Specify page index, start from zero.</param>
        public static IQueryable<T> GetPage<T>(this IOrderedQueryable<T> source, int pageSize, int pageIndex)
        {
            if (null == source)
                throw new ArgumentNullException("source");

            if (pageSize <= 0)
                throw new ArgumentOutOfRangeException("pageSize", "Page size must be greater than zero.");

            if (pageIndex < 0)
                throw new ArgumentOutOfRangeException("pageIndex", "Page index must be greater than or equal to zero.");

            var skip = pageIndex * pageSize;
            if (skip > 0)
                return source.Skip(skip).Take(pageSize);

            return source.Take(pageSize);
        }

        /// <summary>
        /// Gets the query for a specified page of data.
        /// </summary>
        /// <typeparam name="T">The type of the data in the data source.</typeparam>
        /// <param name="source">The data source.</param>
        /// <param name="pageSize">Maximum records of single page, must be greater than zero.</param>
        /// <param name="pageIndex">Specify page index, start from zero.</param>
        public static IEnumerable<T> GetPage<T>(this IOrderedEnumerable<T> source, int pageSize, int pageIndex)
        {
            if (null == source)
                throw new ArgumentNullException("source");

            if (pageSize <= 0)
                throw new ArgumentOutOfRangeException("pageSize", "Page size must be greater than zero.");

            if (pageIndex < 0)
                throw new ArgumentOutOfRangeException("pageIndex", "Page index must be greater than or equal to zero.");

            var skip = pageIndex * pageSize;
            if (skip > 0)
                return source.Skip(skip).Take(pageSize);

            return source.Take(pageSize);
        }
    }
}
